<?php

App::import('Model', 'ConnectionManager');

class MaconnexionComponent extends Object{
	function initialize(&$controller) {        
		// sauvegarde la référence du contrôleur pour une utilisation ultérieure        
		$this->controller =& $controller;    
	}   

	function beforeFilter(&$controller) {
	    $this->Auth->authorize = array('controller');
	    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');

	    $this->Cookie->name = 'CookieMonster';
	}

	//appelée après Controller::beforeFilter()    
	function startup(&$controller) {    
	}

	function beforeRender(&$controller){    
	}

	function beforeRedirect(&$controller){    
	}

	function shutdown(&$controller){    
	}

	public function connect($appli, $local_distant=null) {
		if (isset($appli['Application']['id'])){
			$appli=$appli['Application'];
		}

		if ($local_distant==null){
			$local_distant=$appli['hebergement'];
		}

		$MyConnection=null;

		//SI mode bdd local
		if ($local_distant==0){
			$db =& ConnectionManager::getDataSource ('default');
			$config = $db->config;

			if ($appli['id'] != 0) {
				$datasource = $config['database'];
				$datasource=$datasource.'_$'.$appli['id'];
				$config['database'] = $datasource; 
			}

			try {
				$flags = array(
					//PDO::ATTR_PERSISTENT => $config['persistent'],
					//PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
					PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
				);
				if (!empty($config['encoding'])) {
					$flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
				}
				if (empty($config['unix_socket'])) {
					$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
				} else {
					$dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
				}
				$MyConnection = new PDO(
					$dsn,
					$config['login'],
					$config['password'],
					$flags
				);
				//$this->connected = true;
			} catch (CakeException $e) {
				die();
				throw new MissingConnectionException(array('class' => $e->getMessage()));
			}

			return $MyConnection;
		}
		//Si mode distant
		elseif ($local_distant==1){
			//Si BDD Mysql
			$ApplicationPgdatabase = $appli['pgdatabase_id'];
			$ApplicationHost = $appli['host'];
			$ApplicationPort = $appli['port'];
			$ApplicationSid = $appli['sid'];
			$ApplicationLogin = $appli['login'];
			$ApplicationMdp = $appli['mdp'];
			$ApplicationEncoding = $appli['encoding'];
			$ApplicationUnixSocket = $appli['unixsocket'];

			if($ApplicationPgdatabase==1){
				
					$flags = array(
						//PDO::ATTR_PERSISTENT => $config['persistent'],
						//PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
						PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
					);
					if (!empty($ApplicationEncoding) && $ApplicationEncoding!=null) {
						$flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $ApplicationEncoding;
					}
					if (empty($ApplicationUnixSocket) || $ApplicationUnixSocket==null) {
						$dsn = "mysql:host={$ApplicationHost};port={$ApplicationPort};dbname={$ApplicationSid}";
					} else {
						$dsn = "mysql:unix_socket={$ApplicationUnixSocket};dbname={$ApplicationSid}";
					}

				try {
					$MyConnection = new PDO(
						$dsn,
						$ApplicationLogin,
						$ApplicationMdp,
						$flags
					);
					//$this->connected = true;
				} catch (CakeException $e) {
					die();
					throw new MissingConnectionException(array('class' => $e->getMessage()));

				}

				return $MyConnection;
			}
			//Si BDD Oracle
			elseif ($appli['pgdatabase_id']==2) {
				
				$db = 'oci:dbname='.$ApplicationHost.':'.$ApplicationPort.'/'.$ApplicationSid; 
				if (!empty($ApplicationEncoding) && $ApplicationEncoding!=null) {
					$db=$db.';charset='.$ApplicationEncoding;
				}
				try{
					//e.g. '//192.168.1.1/orcl'
				
					//$db = 'oci:dbname=127.0.0.1:1521/DONYX1';
					$user = $ApplicationLogin;
					$pass = $ApplicationMdp;

					$MyConnection = new PDO($db,$user,$pass);
				}catch(CakeException $e){
					die();
					throw new MissingConnectionException(array('class' => $e->getMessage()));
				}

				return $MyConnection;
			}else{
				throw new MissingConnectionException(array('class' => "Le type de base définie n'éxiste pas. Contactez votre administrateur"));
			}

		}else{
			throw new MissingConnectionException(array('class' => "Aucun type d'hebergement définie pour cette application. Contactez votre administrateur"));
		}
	}

	//Data Definition Language: CREATE, DROP, UPDATE, DELETE...
	public function ddlquery($appli , $requete, $local_distant=null) {
		$MyConnection =& $this->connect($appli, $local_distant);

		if ($requete!=null){
			$reponse = $MyConnection->query($requete);
			//$reponse = $MyConnection->prepare($requete);
			//bh -> exec($requete);
		}
		//debug($reponse->fetch());
		$MyConnection = null;
		//return $reponse->fetch();
	}

	//Data Manipulation Language: SELECT.
	//return tableau
	public function dmlquery($appli , $requete, $local_distant=null) {
		$MyConnection = null;
		$MyConnection =& $this->connect($appli, $local_distant);

		$data=null;

		if($MyConnection!=null){
			$reponse=null;
			if ($requete!=null){
				$reponse = $MyConnection->query($requete);
				//debug($requete);
				//$reponse = $MyConnection->prepare($requete);
				//bh -> exec($requete);
			}
			//debug($reponse->fetch());
			$MyConnection = null;

			$i=0;
			if($reponse!=null){
				while($donnees = $reponse->fetch())
		    	{
		    		$data[$i]=$donnees;
		    		$i=$i+1;
		    		//debug($donnees);
		    	} 
	    		$reponse->closeCursor($reponse);
		    }
	    }
    	//debug();
		return $data;
	}

	//Data Manipulation Language: SELECT.
	//return curseur
	public function p_dmlquery($appli , $requete, $local_distant=null) {
		$MyConnection = null;
		$MyConnection =& $this->connect($appli, $local_distant);

		$reponse=null;
		if ($requete!=null){
			$reponse = $MyConnection->query($requete);
			//$reponse = $MyConnection->prepare($requete);
			//bh -> exec($requete);
		}
		//debug($reponse->fetch());
		$MyConnection = null;
		
		return $reponse;
	}

}